<template>
  <div class="picking">
    <div class="common-loading" v-show="loadings.form">
      <van-loading type="spinner" color="#ed6d00" />
    </div>
    <van-nav-bar title="质检分货" left-text="返回" @click-left="goBack"></van-nav-bar>
    <van-form :show-error-message="false" class="common-form">
      <van-field
        readonly
        clickable
        v-model="form.locationPropertiesName"
        class="locationPropertiesName"
        label="库存属性"
        placeholder="请选择库存属性"
        @click="showPopups.locationProperties = true"
      />
      <van-popup v-model="showPopups.locationProperties" round position="bottom">
        <van-picker
          show-toolbar
          :columns="locationsList"
          value-key="locationPropertiesName"
          @cancel="cancelQALocations"
          @confirm="confirmQALocations"
        />
      </van-popup>
      <van-field
        ref="sourceCartonNumber"
        id="sourceCartonNumber"
        v-model="form.sourceCartonNumber"
        label="原始箱号"
        placeholder="请扫描原始箱号"
        :rules="[{required: true, message: '请扫描原始箱号'}]"
        @keydown.enter.native="!pdaScanData.data ? getSourceCarton() : ''"
        @focus="disableKeyboard('sourceCartonNumber')"
        @click="disableKeyboard('sourceCartonNumber')"
        :readonly="readOnlys.sourceCartonNumber"
        :disabled="showDisabled.sourceCartonNumber"
      />
      <van-field
        ref="cartonNumber"
        id="cartonNumber"
        v-model="form.cartonNumber"
        label="目标箱号"
        placeholder="请扫描目标箱号"
        :rules="[{required: true, message: '请扫描目标箱号'}]"
        @keydown.enter.native="!pdaScanData.data ? scanTargetCarton() : ''"
        @focus="disableKeyboard('cartonNumber')"
        @click="disableKeyboard('cartonNumber')"
        :readonly="readOnlys.cartonNumber"
        :disabled="showDisabled.cartonNumber"
      />
      <van-field
        ref="barCode"
        id="barCode"
        v-model="form.barCode"
        label="SKU"
        placeholder="请扫描SKU"
        :rules="[{required: true, message: '请扫描SKU'}]"
        @keydown.enter.native="!pdaScanData.data ? scanSku() : ''"
        @focus="disableKeyboard('barCode')"
        @click="disableKeyboard('barCode')"
        :readonly="readOnlys.barCode"
      />
      <van-row type="flex" class="picking__num">
        <van-col span="8">
          应分: <span>{{ form.planSortQty }}</span> 件
        </van-col>
        <van-col span="8">
          已分: <span>{{ form.actSortQty }}</span> 件
        </van-col>
        <van-col span="8">
          差异: <span class="red">{{ form.difSortQty }}</span> 件
        </van-col>
      </van-row>
    </van-form>
    <van-row type="flex" class="picking__num" style="margin-top:100px;">
      <van-col span="10">
        <van-button type="primary" size="large" block @click="changeSourceTarget">切原箱</van-button>
      </van-col>
      <van-col span="4"> </van-col>
      <van-col span="10">
        <van-button
          type="primary"
          size="large"
          block
          @click="closeTargetCarton"
          :disabled="!form.targetCartonId"
          :loading="loadings.closeTargetCarton"
          >关箱</van-button
        >
      </van-col>
    </van-row>
    <audio ref="successAudio" :src="successSource"></audio>
    <audio ref="errorAudio" :src="errorSource"></audio>
  </div>
</template>
<script>
import {mapGetters} from "vuex";
import {getQALocations, getSourceCarton, scanTargetCarton, scanSku, closeTargetCarton} from "@/api/biz/quality/quality.js";
const defaultForm = {
  locationPropertiesName: "",
  locationPropertiesId: "",
  sourceCartonNumber: "",
  targetCartonId: "",
  cartonNumber: "",
  barCode: "",
  planSortQty: 0, // "应分数量",
  actSortQty: 0, // "已分数量",
  difSortQty: 0 // "差异数量",
};
const defaultDisabled = {
  sourceCartonNumber: false,
  cartonNumber: false
};
export default {
  name: "picking",
  data() {
    return {
      errorSource: require("@/assets/sound/error.mp3"),
      successSource: require("@/assets/sound/success.mp3"),
      form: {...defaultForm},
      locationsList: [],
      readOnlys: {
        sourceCartonNumber: false,
        cartonNumber: false,
        barCode: false
      },
      showPopups: {
        locationProperties: false
      },
      loadings: {
        closeTargetCarton: false,
        form: false
      },
      showDisabled: {...defaultDisabled}
    };
  },
  mounted() {
    this.getQALocations();
  },
  watch: {
    pdaScanData: {
      handler(data) {
        let input = document.activeElement.id;
        if (input == "sourceCartonNumber") {
          this.form.sourceCartonNumber = data.data;
          this.getSourceCarton();
        } else if (input == "cartonNumber") {
          this.form.cartonNumber = data.data;
          this.scanTargetCarton();
        } else if (input == "barCode") {
          this.form.barCode = data.data;
          this.scanSku();
        }
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters("scanner", ["pdaScanData"]),
    ...mapGetters("user", ["userId", "userData"]),
    storerId() {
      return this.$root.storerWarehouseBrand.storerId;
    },
    wareHouseId() {
      return this.$root.storerWarehouseBrand.warehouseId;
    },
    brandId() {
      return this.$root.storerWarehouseBrand.brandId;
    },
    isValueEmpty() {
      let arry = ["sourceCartonNumber", "cartonNumber", "barCode"];
      let flag = true;
      for (let i = 0; i < arry.length; i++) {
        if (!this.form[arry[i]]) {
          flag = false;
          break;
        }
      }
      return flag;
    }
  },
  methods: {
    // 播放成功提示声
    playSuccessSound() {
      this.$refs["successAudio"].play();
    },
    // 播放错误提示声
    playErrorSound() {
      this.$refs["errorAudio"].play();
    },
    check() {
      let arry = ["sourceCartonNumber", "cartonNumber", "barCode"];
      let flag = true;
      arry.forEach(item => {
        if (flag && !this.form[item]) {
          this.$nextTick(() => {
            setTimeout(() => {
              this.$refs[item].focus();
            }, 300);
          });
          flag = false;
        }
      });
    },
    // 禁用键盘
    disableKeyboard(name) {
      this.readOnlys[name] = true;
      setTimeout(() => {
        this.readOnlys[name] = false;
      }, 200);
    },
    cancelQALocations() {
      this.showPopups.locationProperties = false;
      this.check();
    },
    confirmQALocations(value) {
      this.showPopups.locationProperties = false;
      if (value.locationPropertiesName !== this.form.locationPropertiesName) {
        this.form.cartonNumber = "";
        this.showDisabled.cartonNumber = false;
      }
      this.form.locationPropertiesName = value.locationPropertiesName;
      this.form.locationPropertiesId = value.locationPropertiesId;
      this.check();
    },
    getQALocations() {
      let params = {
        storerId: this.storerId, // "货主ID",
        wareHouseId: this.wareHouseId, // "仓库ID",
        brandId: this.brandId, // "品牌ID",
        loginName: this.userData.sysUserLoginName, // "操作人名称"
        userId: this.userId
      };
      this.loadings.form = true;
      getQALocations(params)
        .then(response => {
          this.loadings.form = false;
          if (response.data.status) {
            // 成功操作
            this.locationsList = response.data.data.locationList;
            this.form.locationPropertiesName = this.locationsList[0].locationPropertiesName;
            this.form.locationPropertiesId = this.locationsList[0].locationPropertiesId;
            this.check();
          } else {
            this.$toast.fail(response.data.message);
          }
          this.$refs.sourceCartonNumber.focus();
        })
        .catch(() => {
          this.loadings.form = false;
          this.$refs.sourceCartonNumber.focus();
          this.$toast.fail("请求出错！");
        });
    },
    getSourceCarton() {
      let params = {
        sourceCartonNumber: this.form.sourceCartonNumber
      };
      this.loadings.form = true;
      getSourceCarton(params)
        .then(response => {
          this.loadings.form = false;
          if (response.data.status) {
            let res = response.data.data;
            this.showDisabled.sourceCartonNumber = true;
            this.form.planSortQty = Number(res.planSortQty);
            this.form.actSortQty = Number(res.actSortQty);
            this.form.difSortQty = Number(res.difSortQty);
            this.check();
          } else {
            this.form.sourceCartonNumber = "";
            this.$toast.fail(response.data.message);
          }
        })
        .catch(() => {
          this.loadings.form = false;
          this.form.sourceCartonNumber = "";
          this.$toast.fail("请求出错！");
        });
    },
    scanTargetCarton() {
      if (!this.form.sourceCartonNumber) {
        this.check();
        return;
      }
      let params = {
        locationPropertiesId: this.form.locationPropertiesId,
        cartonNumber: this.form.cartonNumber
      };
      this.loadings.form = true;
      scanTargetCarton(params)
        .then(response => {
          this.loadings.form = false;
          if (response.data.status) {
            this.form.targetCartonId = response.data.data.targetCartonId;
            this.showDisabled.cartonNumber = true;
            this.check();
          } else {
            this.form.cartonNumber = "";
            this.$toast.fail(response.data.message);
          }
        })
        .catch(() => {
          this.loadings.form = false;
          this.form.cartonNumber = "";
          this.$toast.fail("请求出错！");
        });
    },
    scanSku() {
      if (!this.isValueEmpty) {
        this.playErrorSound();
        this.form.barCode = "";
        this.check();
        return;
      }
      let params = {
        storerId: this.storerId, // "货主ID",
        wareHouseId: this.wareHouseId, // "仓库ID",
        brandId: this.brandId, // "品牌ID",
        loginName: this.userData.sysUserLoginName, // "操作人名称"
        locationPropertiesId: this.form.locationPropertiesId, // "库位属性ID"，
        sourceCartonNo: this.form.sourceCartonNumber, // "原始箱号",
        targetCartonNo: this.form.cartonNumber, // "目标箱号",
        targetCartonId: this.form.targetCartonId, // "目标箱号ID",
        barCode: this.form.barCode // "SKU商品条码",
      };
      this.loadings.form = true;
      scanSku(params)
        .then(response => {
          this.loadings.form = false;
          if (response.data.status) {
            this.playSuccessSound();
            this.$notify(response.data.message);
            this.form.barCode = "";
            this.form.actSortQty = Number(this.form.actSortQty) + 1;
            this.form.difSortQty = Number(this.form.planSortQty) - Number(this.form.actSortQty);
          } else {
            this.playErrorSound();
            this.form.barCode = "";
            this.$toast.fail(response.data.message);
          }
          this.check();
        })
        .catch(() => {
          this.playErrorSound();
          this.loadings.form = false;
          this.form.barCode = "";
          this.$toast.fail("请求出错！");
        });
    },
    changeSourceTarget() {
      if (!this.form.sourceCartonNumber) {
        this.check();
        return;
      }
      this.showDisabled.sourceCartonNumber = false;
      this.form.sourceCartonNumber = "";
      this.form.barCode = "";
      this.check();
    },
    clear() {
      this.form = {...defaultForm};
      this.showDisabled = {...defaultDisabled};
      this.form.locationPropertiesName = this.locationsList[0].locationPropertiesName;
      this.form.locationPropertiesId = this.locationsList[0].locationPropertiesId;
      this.$refs.sourceCartonNumber.focus();
    },
    clearTargetCarton() {
      this.form.barCode = "";
      this.form.targetCartonId = "";
      this.showDisabled.cartonNumber = false;
      this.form.cartonNumber = "";
      this.check();
    },
    closeTargetCarton() {
      if (!this.form.targetCartonId) {
        this.check();
        return;
      }
      let params = {
        targetCartonId: this.form.targetCartonId, // "目标箱号ID",
        loginName: this.userData.sysUserLoginName // "操作人名称"
      };
      this.loadings.closeTargetCarton = true;
      closeTargetCarton(params)
        .then(response => {
          this.loadings.closeTargetCarton = false;
          if (response.data.status) {
            this.$toast.success(response.data.message);
            if (this.form.difSortQty > 0) {
              this.clearTargetCarton();
            } else {
              this.clear();
            }
          } else {
            this.$toast.fail(response.data.message);
          }
        })
        .catch(() => {
          this.loadings.closeTargetCarton = false;
          this.form.barCode = "";
          this.$toast.fail("请求出错！");
        });
    },
    goBack() {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="less" scoped>
.picking {
  .locationPropertiesName {
    /deep/ .van-field__control {
      color: red;
      font-weight: bold;
      font-size: 18px;
    }
  }
  &__num {
    padding: 10px 16px;
    font-size: 14px;
    color: #333;
    span {
      margin-left: 8px;
      margin-right: 4px;
    }
    .red {
      color: red;
    }
  }
}
</style>
